<?php
namespace yunj;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use yunj\validate\Qiniu as QiniuValidate;

/**
 * 七牛云
 * Class Config
 * @package yunj
 */
final class Qiniu{

    private $access_key;

    private $secret_key;

    private $bucket;

    private $domain;

    private $validate;

    private $config;

    // 上传key
    private $key;

    // 上传文件地址
    private $file_path;

    // 成功响应结果
    private $response;

    // 失败响应结果
    private $error;

    private function __construct() {
        $this->setAttr();
    }

    private function setAttr(){
        $this->validate=new QiniuValidate();
        // 验证是否引入composer 七牛云SDK
        if(!class_exists('\\Qiniu\\Auth')) throw new \Exception('请通过composer引入七牛云SDK');
        // 验证配置
        $config=yunj_config('qiniu');
        $res=$this->validate->scene('config')->check($config);
        if(!$res) throw new \Exception($this->validate->getError());
        $config=$this->validate->getData();
        $this->access_key=$config['access_key'];
        $this->secret_key=$config['secret_key'];
        $this->bucket=$config['bucket'];
        $this->domain=$config['domain'];
        $this->config=$config;
    }

    private static $instance;

    public static function instance(){
        if (!self::$instance instanceof self){
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Notes: 文件上传
     * Author: Uncle-L
     * Date: 2020/11/3
     * Time: 17:46
     * @param $key          [上传的key]
     * @param $file_path    [上传文件路径]
     * @return $this
     * @throws \Exception
     */
    public function upload($key,$file_path){
        $auth = new Auth($this->access_key, $this->secret_key);
        $token = $auth->uploadToken($this->bucket);
        $uploadMgr = new UploadManager();
        list($response, $error) = $uploadMgr->putFile($token, $key, $file_path);
        if($error) throw new \Exception(is_string($error)?$error:json_encode($error));
        $this->key=$key;
        $this->file_path=$file_path;
        $this->response=$response;
        $this->error=$error;
        return $this;
    }

    /**
     * Notes: 获取文件url
     * Author: Uncle-L
     * Date: 2020/11/3
     * Time: 17:47
     * @return string
     */
    public function url(){
        return $this->domain.'/'.$this->key;
    }

}